package com.atstudy.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @version v1.0
 * @description:
 * @author: admin
 * @date: 2023/2/3 10:39
 * @copyright: 博为峰
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodName = req.getParameter("method");

        Class<? extends BaseServlet> cla = this.getClass();
        Method method = null;
        try {
            method = cla.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("调用的方法不存在: " + methodName);
        }

        try {
            String result = (String) method.invoke(this, req, resp);
            String action = result.substring(0, result.indexOf(":"));
            String path = result.substring(result.indexOf(":") + 1);
            if (action.equals("forward")) {
                req.getRequestDispatcher(path).forward(req, resp);
            } else if (action.equals("redirect")) {
                resp.sendRedirect(req.getContextPath() + path);
            }
        } catch (Exception e) {
            throw new RuntimeException("调用的方法异常: " + methodName);
        }
    }
}
